package com.yupi.job;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.model.domain.Userinfo;
import com.yupi.service.UserinfoService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存预热任务
 */
@Component
@Slf4j

public class PreCacheJob {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RedissonClient redissonClient;
    @Resource
    private UserinfoService userinfoService;

    //每天加载，预热推荐用户 每天十点05预热
    @Scheduled(cron = "0 36 21 * * ? ")
    public void doCacheRecommendUser() {
        //给重点用户预热
        List<Long> mainUserList = Arrays.asList(1l, 2l, 3l, 5l, 8l);
        //1.获取分布式锁
        RLock lock = redissonClient.getLock("dogfriend:precachejob:docache:lock");
        //2.尝试获取锁 参数  等待时间0 因为该定时任务每天只执行一次，只抢一次，没拿到锁就不用再来了    施放时间：拿到锁后多久后释放
        //只有一个线程能获取到锁
        System.out.println("lock:" + Thread.currentThread().getId());
        try {
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                mainUserList.forEach(userId -> {
                    String redisKey = String.format("dogfriend:user:recommend:%s", userId);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    Page<Userinfo> uesrPage = userinfoService.page(new Page<>(1, 20), null);
                    try {
                        valueOperations.set(redisKey, uesrPage, 100, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                });
            }

        } catch (InterruptedException e) {
            log.error("redis set key error ", e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                //只能释放当前线程加的锁
                lock.unlock();
                System.out.println("unlock:" + Thread.currentThread().getId());
            }

        }


    }

}
